'use strict';

var helper = function() {
  return {
    getElemPath: function(elem) {
      var array = [];
      // if (elem.nodeType == 3) {
      var obj = {};

      obj.id = elem.id.trim();
      obj.tag = elem.tagName.toLowerCase();
      obj.classname = elem.className.trim();

      while (obj.tag.indexOf('body') == -1) {

        var tempClass = '';
        var tempId = '';
        if (obj.classname.length) {
          tempClass = '.' + obj.classname.replace(/\s{2,}/, ' ').split(
            ' ').join('.');
        }
        if (obj.id.length) {
          tempId = '#' + obj.id;
        }
        var str = obj.tag + tempId + tempClass;
        array.push(str);
        elem = $(elem).parent()[0];

        obj.id = elem.id.trim();
        obj.tag = elem.tagName.toLowerCase();
        obj.classname = elem.className.trim();
      }
      // }
      return array.reverse().join(' > ');
    },
    getXPath:function (elt) {
      return getElementXPath(elt);
      function getElementXPath(elt){  
        var path = "";   
        for (; elt && elt.nodeType == 1; elt = elt.parentNode)   
        {        
          var idx = getElementIdx(elt);        
          var xname = elt.tagName.toLowerCase();     
          if (idx > 1) xname += "[" + idx + "]";       
          path = "/" + xname + path;   
        }
        return path;    
      }

      // Get Idx of an element
      function getElementIdx(elt){    
        var count = 1;    
        for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling)    
        {        
          if(sib.nodeType == 1 && sib.tagName == elt.tagName)  count++    
        }        
        return count;
      }

    }
  };
};

helper.$inject = [];
var app = angular.module('webpageApp');
app.factory('helper', helper);
